package com.lmx.repoDomain.repository;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.persistence.service.NursingService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.ServiceFinishLevel;

import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

@JsonApiResourceRepository(ServiceFinishLevel.class)
@Component
public class ServiceFinishLevelRepository extends BaseRepository<ServiceFinishLevel> {

	@Autowired
	private NursingService nursingService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(ServiceFinishLevel.class);
	}

	@Override
	@JsonApiSave
	public ServiceFinishLevel save(ServiceFinishLevel data) {
		if (data.getId() == null) {// create
			ServiceFinishLevel temp = nursingService.getFinishLevelByName(data);
			if (temp == null) {
				nursingService.createServiceFinishLevel(data);
			} else {
				data.setErrcode(4);// 名字重复
				throw new BusinessException(null, CommonConstants.ERROR_CODE.NAME_ERROR.label(), null);
			}
		} else {// update
			if (data.getDelStatus() == 1) {// 删除
				int deleteFlag = nursingService.checkFinishLevelRelations(data);
				if (deleteFlag > 0) {
					data.setErrcode(8);// no delete
					throw new BusinessException(null, CommonConstants.ERROR_CODE.NO_DELETE.label(), null);
				}
			} else {
				ServiceFinishLevel temp = nursingService.getFinishLevelByNameFilterId(data);
				if (temp == null) {
					dslJpaService.update(data);
				} else {
					data.setErrcode(4);
					throw new BusinessException(null, CommonConstants.ERROR_CODE.NAME_ERROR.label(), null);
				}
			}
		}
		return data;
	}

}
